<?php

namespace lifanko;

class Visits
{
    private string $id;
    private string $extra;

    public static int $now;

    public function __construct($extra, $id = 'auto')
    {
        self::$now = time();
        $this->extra = $extra;

        if ($id == 'auto') {
            $this->id = substr($_SERVER['PHP_SELF'], strrpos($_SERVER['PHP_SELF'], '/') + 1, -4);
        } else {
            $this->id = $id;
        }
    }

    public function update()
    {
        $filename = $this->extra . 'visits_' . $this->id . '.txt';
        if (!is_file($filename)) {
            file_put_contents($filename, '');
        }

        $str_lack = '';
        for ($i = count(file($filename)); $i <= intval(date('H')); $i++) {
            $leader = range('A', 'Z')[$i];
            $str_lack .= ($i == 0 ? '' : "\n") . $leader;
        }

        file_put_contents($filename, $str_lack . '*', FILE_APPEND);
        $visits = strlen(file_get_contents($filename)) - 2 * $i + 1;

        $filename_history = $this->extra . 'visits_' . $this->id . '_history.json';
        if (!is_file($filename_history)) {
            file_put_contents($filename_history, '{}');
        }
        $visits_history = json_decode(file_get_contents($filename_history), true);
        $date = date('Y-m-d', self::$now);

        if (!isset($visits_history[$date])) {
            if (count($visits_history) > 0) {
                if (end($visits_history) == '?') {
                    $visits_history[key($visits_history)] = $visits;
                }
            }

            $visits_history[$date] = '?';
            file_put_contents($filename_history, json_encode($visits_history));
            file_put_contents($filename, '');

            $sum = 0;
        } else {
            $sum = $visits;
        }

        $visits_history = array_values($visits_history);
        foreach ($visits_history as $val) {
            if (is_numeric($val)) {
                $sum += $val;
            }
        }

        return $sum;
    }
}